import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { ProductVariant } from '../../../product/domain';
import { DialogService } from 'src/app/dialog';

@Component({
  selector: 'app-product-variant-dialog',
  templateUrl: './product-variant-dialog.component.html',
  styleUrls: ['./product-variant-dialog.component.css']
})
export class ProductVariantDialogComponent implements OnInit {
  @Input() variants: ProductVariant[] = [];
  @Output() formSubmitted = new EventEmitter();
  @Output() selected = new EventEmitter<number>();
  @Input() selectedVariantIndex = 0;
  count = 0;
  constructor(private dialogService: DialogService) { }

  ngOnInit() {
  }
  
  get price () {
    if(this.selectedVariantIndex < 0 && this.variants.length === 0) {
      return 0;
    }
    return this.variants[this.selectedVariantIndex].price;
  }

  get selectedVariantImage () {
    if(this.selectedVariantIndex < 0 && this.variants.length === 0) {
      return '';
    }
    return this.variants[this.selectedVariantIndex].productVariantImages[0]
      .imgUrl;
  }

  get selectedVariantName () {
    if(this.selectedVariantIndex < 0 && this.variants.length === 0) {
      return '';
    }
    return this.variants[this.selectedVariantIndex].name;
  }

  handleSelection (idx) {
    console.log(88, idx);
    this.selectedVariantIndex = idx;
    this.selected.emit(this.selectedVariantIndex);
  }

  handleAmountChange (count: number) {
    console.log(99, count);
    this.count = count;
  }

  handleConfirm () {
    if(this.selectedVariantIndex < 0 && this.variants.length === 0) {
      return;
    }
    // 点击对话框的确认按钮，将{ variant:..., count:... }提交给下一个页面
    this.formSubmitted.emit({
      variant: this.variants[this.selectedVariantIndex],
      count: this.count
    })
    this.dialogService.close();
  }
}